package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

@Slf4j
@RestController
@RequestMapping("/user")
@ResponseBody
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 发送手机验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMgh(@RequestBody User user, HttpSession httpSession) {
        //获取手机号
        String phone = user.getPhone();
        //生成验证码
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code=" + code);
            //SMSUtils.sendMessage("瑞吉外卖", "", phone, code);
            httpSession.setAttribute(phone, code);
            return R.success("短信发送成功");
        }
        return R.error("输入的手机号码不正确发送失败");
    }

    @PostMapping("/login")
    public R loginUser(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        return userService.login(request, loginDto);
    }
    @PostMapping("/loginout")
    public R  loginOutUser(HttpServletRequest request){
        return userService.loginOut(request);
    }
}

